package cas.ihep.hmss;

import cas.ihep.hmss.proto.HmssProtos;
import cas.ihep.hmss.queue.JobQueue;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

public class ServerHandler extends ChannelInboundHandlerAdapter{

    private JobQueue queue;
    private AtomicInteger increment;

    ServerHandler(JobQueue q){
        queue=q;
        increment=new AtomicInteger(0);
    }
    public void channelRead(ChannelHandlerContext ctx,Object obj){

        HmssProtos.JobSubmitRequest req = (HmssProtos.JobSubmitRequest) obj;
        Job job =new Job();
        job.destPath =req.getDestination();
        job.srcPath = req.getSourceList();
        job.group = req.getGroup();
        job.user = req.getUser();
        job.priority = req.getPriority();
        job.enqueueTime = System.currentTimeMillis();
        job.jid = job.user + Long.toHexString(job.enqueueTime)+Integer.toHexString(increment.getAndIncrement());
        try {
            queue.enqueue(job);
            HmssProtos.JobSubmitResponse.Builder builder=HmssProtos.JobSubmitResponse.newBuilder();
            builder.setMsg(job.jid);
            ctx.writeAndFlush(builder.build());
            //System.out.println("==="+job.srcPath+"==="+job.destPath+"==="+job.group+"==="+job.user+"==="+job.priority);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
